package com.tanhua.sso.server.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.api.config.filter.IFilterConfig;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.api.*;
import com.tanhua.autoconfig.tmplate.OssTemplate;
import com.tanhua.config.UserHolder;
import com.tanhua.exceptionhander.CustomException;
import com.tanhua.result.Result;
import com.tanhua.sso.pojo.Comment;
import com.tanhua.sso.pojo.FocusUser;
import com.tanhua.sso.pojo.UserInfo;
import com.tanhua.sso.pojo.Video;
import com.tanhua.sso.utils.CommentType;
import com.tanhua.sso.vo.VideoVo;
import com.tanhua.util.Constants;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class SmallVideosService {

    @DubboReference
    private VideoServiceApi videoServiceApi;

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @DubboReference
    private UserInfoService userInfoService;

    @DubboReference
    private FocusUserServiceApi focusUserServiceApi;

    @DubboReference
    private CommentsServiceApi commentsServiceApi;

    @Autowired
    private MessagesService messagesService;

    @DubboReference
    private MovementsService movementsService;

    @Autowired
    private CommentsService commentsService;

    @Autowired
    private AppMqMessageService appMqMessageService;


    /*上传视频
    * videoThumbnail 封面
    * videoFile 视频*/
    //清空缓存
    @CacheEvict(value = "videos",allEntries = true)
    public void smallVideos(MultipartFile videoThumbnail, MultipartFile videoFile) {
        //mq发送信息
        appMqMessageService.sendLogService(UserHolder.getUserId(),"0301","Video",null);
        //先将封面上传到阿里云
        try {
            String upload = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
                //获取文件格式
                int lastIndexOf = videoFile.getOriginalFilename().lastIndexOf(".");
                String format = videoFile.getOriginalFilename().substring(lastIndexOf + 1);
                //上传,返回文件路径
                StorePath storePath = fastFileStorageClient.uploadFile(videoFile.getInputStream(), videoFile.getSize(), format, null);
                //拼接文件路径
                String  uri = fdfsWebServer.getWebServerUrl()+"/"+storePath.getFullPath();
                //存入数据库
            Video video=new Video();
            video.setVideoUrl(uri);
            video.setCreated(System.currentTimeMillis());
            video.setPicUrl(upload);
            video.setText("探花测试视频");
            video.setUserId(UserHolder.getUserId());
            videoServiceApi.save(video);
        } catch (Exception e) {
            throw new CustomException("上传失败");
        }
    }

    @Cacheable(value = "videos",key = "T(com.tanhua.config.UserHolder).getUserId()+'_'+#page+'_'+#pagesize",unless = "#result.items==null")
    /*查看视频列表*/
    public Result selectSmallVideos(Integer page, Integer pagesize) {

        List<Video> videoList=new ArrayList<>();
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        int totalPage=0;
        //查看当前用户是否有推荐shipin
        String vid = redisTemplate.opsForValue().get(Constants.VIDEOS_RECOMMEND + userId);
        if (StrUtil.isNotEmpty(vid)){
            String[] ids = vid.split(",");
            //判断推荐的视频是否满足分页查询条件
            if ((page-1)*pagesize<ids.length){
                List<Long> vids = Arrays.stream(ids).skip((page - 1) * pagesize).limit(pagesize)
                        .map(s -> Convert.toLong(s)).collect(Collectors.toList());
                //查看推荐视频
                videoList=videoServiceApi.selectByVids(vids);
            }
            //获取推荐总页数
            totalPage = PageUtil.totalPage(ids.length, pagesize);
        }else {
            videoList=videoServiceApi.selectPage(page-totalPage,pagesize);
        }

        List<VideoVo> videoVoList=new ArrayList<>();
        //封装Vo对象
        for (Video video : videoList) {
            UserInfo userInfo = userInfoService.selectUser(video.getUserId());
            VideoVo videoVo = VideoVo.init(userInfo, video);
            //查看是否关注
            boolean flag=focusUserServiceApi.isHasFocus(video.getUserId(),UserHolder.getUserId());
            //设置关注
            if (flag){
                videoVo.setHasFocus(1);
            }
            //查看是否点赞
            int type = CommentType.LIKE.getType();
            Integer like = commentsServiceApi.findMyLike(UserHolder.getUserId(), video.getId());
            //设置点赞
            if (ObjectUtil.isEmpty(like)){
                videoVo.setHasLiked(1);
            }
            videoVoList.add(videoVo);
        }

        return new Result(videoVoList.size(),pagesize,100,page,videoVoList);
    }

    //视频用户关注
    public void userFocus(Long uid) {
        //获取当前用户
        Long userId = UserHolder.getUserId();
        //从redis中查看是否已关注
        String key = Constants.FOCUS_USER_KEY + UserHolder.getUserId();
        String hashKey = String.valueOf(uid);
        String isOne = (String) redisTemplate.opsForHash().get(key, hashKey);
        if (StrUtil.isNotEmpty(isOne)){
            throw new CustomException("已经关注住过了");
        }
        FocusUser focusUser=new FocusUser();
        focusUser.setUserId(userId);
        focusUser.setFollowUserId(uid);
        focusUser.setCreated(System.currentTimeMillis());
        focusUserServiceApi.save(focusUser);
        //存入redis
        redisTemplate.opsForHash().put(key,hashKey,"1");
        //查看她是否关注我
        boolean flag=focusUserServiceApi.isHasFocus(uid,userId);
        //加好友
        if (flag){
            messagesService.contacts(uid);
        }
    }

    //取消关注
    public void userUnFocus(Long uid) {
        //获取当前用户
        Long userId = UserHolder.getUserId();
        //从redis中查看是否已关注
        String key = Constants.FOCUS_USER_KEY + UserHolder.getUserId();
        String hashKey = String.valueOf(uid);
        String isOne = (String) redisTemplate.opsForHash().get(key, hashKey);
        if (StrUtil.isEmpty(isOne)){
            throw new CustomException("没有关注");
        }
        redisTemplate.opsForHash().delete(key,hashKey);
        //取消关注
        focusUserServiceApi.delectFocus(uid,userId);
        //删除好友
        messagesService.deleteFriend(uid);
    }


    /*点赞*/
    public void like(ObjectId id) {
        //mq发送信息
        appMqMessageService.sendLogService(UserHolder.getUserId(),"0302","Video",id.toHexString());
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //查看redis中是否点赞
        String key = Constants.VIDEO_LIKE_HASHKEY + UserHolder.getUserId();
        String hashKey = String.valueOf(id);
        String isOne = (String) redisTemplate.opsForHash().get(key, hashKey);
        if (StrUtil.isNotEmpty(isOne)){
            throw new CustomException("我已点过赞了");
        }
        Comment comment=new Comment();
        //封装类型
        comment.setCommentType(CommentType.LIKE.getType());
        //设置动态id
        comment.setPublishId(id);
        //设置创建时间
        comment.setCreated(System.currentTimeMillis());
        //点赞人id
        comment.setUserId(userId);
        commentsServiceApi.saveVideoLike(comment);
        redisTemplate.opsForHash().put(key,hashKey,"1");
    }

    /*取消点赞*/
    public void dislike(ObjectId id) {
        //mq发送信息
        appMqMessageService.sendLogService(UserHolder.getUserId(),"0303","Video",id.toHexString());
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //查看redis中是否点赞
        String key = Constants.VIDEO_LIKE_HASHKEY + UserHolder.getUserId();
        String hashKey = String.valueOf(id);
        String isOne = (String) redisTemplate.opsForHash().get(key, hashKey);
        if (StrUtil.isEmpty(isOne)){
            throw new CustomException("没有点赞");
        }
        redisTemplate.opsForHash().delete(key,hashKey);
        commentsServiceApi.disVideoLike(id,userId);
    }

    //评论列表
    public Result commentsPage(Integer page, Integer pagesize, ObjectId id) {
        Result comments = commentsService.getComments(page, pagesize, id.toHexString());
        return comments;
    }

    //发布评论
    public void sendComments(ObjectId id,String comment) {
        //mq发送信息
        appMqMessageService.sendLogService(UserHolder.getUserId(),"0304","Video",id.toHexString());
        //获取当前用户ia
        Long userId = UserHolder.getUserId();
        Comment newComment=new Comment();
        newComment.setPublishId(id);
        newComment.setContent(comment);
        newComment.setCommentType(CommentType.COMMENT.getType());
        newComment.setCreated(System.currentTimeMillis());
        newComment.setUserId(userId);
        newComment.setLikeCount(0);
        commentsServiceApi.saveVideoComment(newComment);
    }
}
